from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.Qt import QMainWindow
from PyQt5.QtCore import QSize
from PyQt5.QtWidgets import QListWidgetItem, QWidget, QHBoxLayout, QVBoxLayout, QLabel, QPushButton, QListWidget, \
    QMessageBox

import connector.DatabaseDriver as DatabaseDriver
import dao.GoodDao as GoodDao
import dao.TypeDao as TypeDao
import tools
from tools import MessageBoxTools

class goodsManagementPage(QMainWindow):
    def __init__(self, user_id: int):
        super().__init__()
        try:
            self.user_id = user_id
            self.driver: DatabaseDriver.DatabaseDriver = DatabaseDriver.DatabaseDriver()
            print("Database driver initialized successfully.")  # Debug print statement
            self.setupUi()
            self.load_goods_types()
            self.show()
            print("UI setup completed.")  # Debug print statement
        except Exception as e:
            print(f"Initialization error: {e}")  # Debug print statement

    def setupUi(self):
        try:
            self.setObjectName("MainWindow")
            self.resize(1205, 677)
            self.centralwidget = QtWidgets.QWidget(self)
            self.centralwidget.setObjectName("centralwidget")
            self.toolBox = QtWidgets.QToolBox(self.centralwidget)
            self.toolBox.setGeometry(QtCore.QRect(30, 20, 881, 571))
            font = QtGui.QFont()
            font.setFamily("Agency FB")
            font.setPointSize(16)
            self.toolBox.setFont(font)
            self.toolBox.setObjectName("toolBox")
            self.page = QtWidgets.QWidget()
            self.page.setGeometry(QtCore.QRect(0, 0, 881, 477))
            self.page.setObjectName("page")
            self.goods_name_search_edit = QtWidgets.QLineEdit(self.page)
            self.goods_name_search_edit.setGeometry(QtCore.QRect(130, 0, 141, 41))
            self.goods_name_search_edit.setObjectName("goods_name_search_edit")
            self.search_btn = QtWidgets.QPushButton(self.page)
            self.search_btn.setGeometry(QtCore.QRect(660, 50, 111, 51))
            font = QtGui.QFont()
            font.setFamily("Agency FB")
            font.setPointSize(16)
            self.search_btn.setFont(font)
            self.search_btn.setObjectName("search_btn")
            self.goods_id_search_edit = QtWidgets.QLineEdit(self.page)
            self.goods_id_search_edit.setGeometry(QtCore.QRect(430, 0, 141, 41))
            self.goods_id_search_edit.setObjectName("goods_id_search_edit")
            self.goods_type_search_box = QtWidgets.QComboBox(self.page)
            self.goods_type_search_box.setGeometry(QtCore.QRect(130, 50, 141, 41))
            self.goods_type_search_box.setObjectName("goods_type_search_box")
            self.label = QtWidgets.QLabel(self.page)
            self.label.setGeometry(QtCore.QRect(10, 0, 111, 31))
            font = QtGui.QFont()
            font.setFamily("Agency FB")
            font.setPointSize(16)
            self.label.setFont(font)
            self.label.setObjectName("label")
            self.label_2 = QtWidgets.QLabel(self.page)
            self.label_2.setGeometry(QtCore.QRect(10, 50, 111, 31))
            font = QtGui.QFont()
            font.setFamily("Agency FB")
            font.setPointSize(16)
            self.label_2.setFont(font)
            self.label_2.setObjectName("label_2")
            self.label_3 = QtWidgets.QLabel(self.page)
            self.label_3.setGeometry(QtCore.QRect(300, 0, 111, 31))
            font = QtGui.QFont()
            font.setFamily("Agency FB")
            font.setPointSize(16)
            self.label_3.setFont(font)
            self.label_3.setObjectName("label_3")
            self.label_9 = QtWidgets.QLabel(self.page)
            self.label_9.setGeometry(QtCore.QRect(300, 50, 111, 31))
            font = QtGui.QFont()
            font.setFamily("Agency FB")
            font.setPointSize(16)
            self.label_9.setFont(font)
            self.label_9.setObjectName("label_9")
            self.goods_price_search_edit = QtWidgets.QLineEdit(self.page)
            self.goods_price_search_edit.setGeometry(QtCore.QRect(430, 50, 141, 41))
            self.goods_price_search_edit.setObjectName("goods_price_search_edit")
            self.label_10 = QtWidgets.QLabel(self.page)
            self.label_10.setGeometry(QtCore.QRect(590, 0, 141, 31))
            font = QtGui.QFont()
            font.setFamily("Agency FB")
            font.setPointSize(16)
            self.label_10.setFont(font)
            self.label_10.setObjectName("label_10")
            self.goods_supplier_search_edit = QtWidgets.QLineEdit(self.page)
            self.goods_supplier_search_edit.setGeometry(QtCore.QRect(730, 0, 141, 41))
            self.goods_supplier_search_edit.setObjectName("goods_supplier_search_edit")
            self.goods_listView = QListWidget(self.page)
            self.goods_listView.setGeometry(QtCore.QRect(10, 110, 851, 361))
            self.goods_listView.setObjectName("goods_listView")
            self.toolBox.addItem(self.page, "")
            self.page_2 = QtWidgets.QWidget()
            self.page_2.setGeometry(QtCore.QRect(0, 0, 881, 477))
            self.page_2.setObjectName("page_2")
            self.label_4 = QtWidgets.QLabel(self.page_2)
            self.label_4.setGeometry(QtCore.QRect(10, 10, 111, 41))
            font = QtGui.QFont()
            font.setFamily("Agency FB")
            font.setPointSize(16)
            self.label_4.setFont(font)
            self.label_4.setObjectName("label_4")
            self.label_5 = QtWidgets.QLabel(self.page_2)
            self.label_5.setGeometry(QtCore.QRect(300, 10, 111, 41))
            font = QtGui.QFont()
            font.setFamily("Agency FB")
            font.setPointSize(16)
            self.label_5.setFont(font)
            self.label_5.setObjectName("label_5")
            self.label_6 = QtWidgets.QLabel(self.page_2)
            self.label_6.setGeometry(QtCore.QRect(300, 70, 111, 31))
            font = QtGui.QFont()
            font.setFamily("Agency FB")
            font.setPointSize(16)
            self.label_6.setFont(font)
            self.label_6.setObjectName("label_6")
            self.label_8 = QtWidgets.QLabel(self.page_2)
            self.label_8.setGeometry(QtCore.QRect(10, 130, 111, 41))
            font = QtGui.QFont()
            font.setFamily("Agency FB")
            font.setPointSize(16)
            self.label_8.setFont(font)
            self.label_8.setObjectName("label_8")
            self.goods_id_edit = QtWidgets.QLineEdit(self.page_2)
            self.goods_id_edit.setGeometry(QtCore.QRect(130, 10, 131, 41))
            self.goods_id_edit.setObjectName("goods_id_edit")
            self.goods_name_edit = QtWidgets.QLineEdit(self.page_2)
            self.goods_name_edit.setGeometry(QtCore.QRect(430, 10, 131, 41))
            self.goods_name_edit.setObjectName("goods_name_edit")
            self.goods_num_box = QtWidgets.QSpinBox(self.page_2)
            self.goods_num_box.setGeometry(QtCore.QRect(430, 70, 131, 31))
            self.goods_num_box.setObjectName("goods_num_box")
            self.goods_type_box = QtWidgets.QComboBox(self.page_2)
            self.goods_type_box.setGeometry(QtCore.QRect(130, 140, 131, 31))
            self.goods_type_box.setObjectName("goods_type_box")
            self.goods_add_btn = QtWidgets.QPushButton(self.page_2)
            self.goods_add_btn.setGeometry(QtCore.QRect(640, 20, 101, 41))
            font = QtGui.QFont()
            font.setFamily("Agency FB")
            font.setPointSize(16)
            self.goods_add_btn.setFont(font)
            self.goods_add_btn.setObjectName("goods_add_btn")
            self.goods_del_btn = QtWidgets.QPushButton(self.page_2)
            self.goods_del_btn.setGeometry(QtCore.QRect(640, 90, 101, 41))
            font = QtGui.QFont()
            font.setFamily("Agency FB")
            font.setPointSize(16)
            self.goods_del_btn.setFont(font)
            self.goods_del_btn.setObjectName("goods_del_btn")
            self.goods_update_btn = QtWidgets.QPushButton(self.page_2)
            self.goods_update_btn.setGeometry(QtCore.QRect(640, 160, 101, 41))
            font = QtGui.QFont()
            font.setFamily("Agency FB")
            font.setPointSize(16)
            self.goods_update_btn.setFont(font)
            self.goods_update_btn.setObjectName("goods_update_btn")
            self.goods_price_edit = QtWidgets.QLineEdit(self.page_2)
            self.goods_price_edit.setGeometry(QtCore.QRect(130, 70, 131, 41))
            self.goods_price_edit.setObjectName("goods_price_edit")
            self.goods_supplier_edit = QtWidgets.QLineEdit(self.page_2)
            self.goods_supplier_edit.setGeometry(QtCore.QRect(430, 140, 131, 41))
            self.goods_supplier_edit.setObjectName("goods_supplier_edit")
            self.label_7 = QtWidgets.QLabel(self.page_2)
            self.label_7.setGeometry(QtCore.QRect(10, 70, 111, 31))
            font = QtGui.QFont()
            font.setFamily("Agency FB")
            font.setPointSize(16)
            self.label_7.setFont(font)
            self.label_7.setObjectName("label_7")
            self.label_11 = QtWidgets.QLabel(self.page_2)
            self.label_11.setGeometry(QtCore.QRect(300, 130, 111, 31))
            font = QtGui.QFont()
            font.setFamily("Agency FB")
            font.setPointSize(16)
            self.label_11.setFont(font)
            self.label_11.setObjectName("label_11")
            self.toolBox.addItem(self.page_2, "")
            self.setCentralWidget(self.centralwidget)
            self.menubar = QtWidgets.QMenuBar(self)
            self.menubar.setGeometry(QtCore.QRect(0, 0, 1205, 30))
            self.menubar.setObjectName("menubar")
            self.setMenuBar(self.menubar)
            self.statusbar = QtWidgets.QStatusBar(self)
            self.statusbar.setObjectName("statusbar")
            self.setStatusBar(self.statusbar)

            self.retranslateUi()
            self.toolBox.setCurrentIndex(0)
            QtCore.QMetaObject.connectSlotsByName(self)

            self.goods_add_btn.clicked.connect(self.goods_add)
            self.goods_del_btn.clicked.connect(self.goods_delete)
            self.goods_update_btn.clicked.connect(self.goods_update)
            self.search_btn.clicked.connect(self.goods_search)
            self.goods_items_fresh()
        except Exception as e:
            print(f"UI setup error: {e}")  # Debug print statement

    def retranslateUi(self):
        _translate = QtCore.QCoreApplication.translate
        self.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.search_btn.setText(_translate("MainWindow", "查找"))
        self.label.setText(_translate("MainWindow", "商品名："))
        self.label_2.setText(_translate("MainWindow", "商品类别："))
        self.label_3.setText(_translate("MainWindow", "商品编号："))
        self.label_9.setText(_translate("MainWindow", "商品单价："))
        self.label_10.setText(_translate("MainWindow", "供应商名称："))
        self.toolBox.setItemText(self.toolBox.indexOf(self.page), _translate("MainWindow", "商品管理"))
        self.label_4.setText(_translate("MainWindow", "商品编号："))
        self.label_5.setText(_translate("MainWindow", "商品名："))
        self.label_6.setText(_translate("MainWindow", "商品数量："))
        self.label_8.setText(_translate("MainWindow", "商品类别："))
        self.goods_add_btn.setText(_translate("MainWindow", "添加"))
        self.goods_del_btn.setText(_translate("MainWindow", "删除"))
        self.goods_update_btn.setText(_translate("MainWindow", "修改"))
        self.label_7.setText(_translate("MainWindow", "商品单价："))
        self.label_11.setText(_translate("MainWindow", "供应商名称："))
        self.toolBox.setItemText(self.toolBox.indexOf(self.page_2), _translate("MainWindow", "增加商品"))


    def load_goods_types(self):
        try:
            self.goods_type_search_box.addItem("所有", None)  # 添加 "所有" 选项
            self.goods_type_box.addItem("所有", None)  # 添加 "所有" 选项
            types = TypeDao.get_all_types(self.driver)
            print(f"Types loaded: {types}")  # Debug print statement
            for type_ in types:
                self.goods_type_search_box.addItem(type_[1], type_[0])  # 显示名称，保存ID
                self.goods_type_box.addItem(type_[1], type_[0])  # 显示名称，保存ID
        except Exception as e:
            print(f"Error loading goods types: {e}")  # Debug print statement

    def goods_items_fresh(self):
        try:
            good_list = GoodDao.get_all_good(self.driver)
            self.goods_listView.clear()
            for good in good_list:
                item = QListWidgetItem(self.goods_listView)
                item.setSizeHint(QSize(850, 50))
                widget = QWidget()
                layout = QHBoxLayout()

                label_id = QLabel("编号: " + str(good[0]))
                label_name = QLabel("名称: " + str(good[1]))
                label_supplier = QLabel("供应商: " + str(good[2]))
                label_type_name = QLabel("类别: " + str(good[3]))
                label_num = QLabel("数量: " + str(good[4]))  # 显示数量

                try:
                    label_price = QLabel("价格: " + f"{float(good[5]):.2f}")  # 确保价格显示为两位小数
                except ValueError:
                    label_price = QLabel("价格: " + str(good[5]))  # 如果不能转换为浮点数，显示原始值

                layout.addWidget(label_id)
                layout.addWidget(label_name)
                layout.addWidget(label_type_name)
                layout.addWidget(label_supplier)
                layout.addWidget(label_num)  # 添加数量标签到布局
                layout.addWidget(label_price)  # 添加价格标签到布局

                widget.setLayout(layout)
                self.goods_listView.addItem(item)
                self.goods_listView.setItemWidget(item, widget)
        except Exception as e:
            print(f"Error refreshing goods items: {e}")  # Debug print statement

    def goods_search(self):
        try:
            if self.goods_id_search_edit.text() == "" and self.goods_name_search_edit.text() == "" and \
                    self.goods_type_search_box.currentData() == None and self.goods_price_search_edit.text() == "" and \
                    self.goods_supplier_search_edit.text() == "":
                self.goods_items_fresh()
                MessageBoxTools.information('提醒', "请输入内容",
                                            buttons=QMessageBox.Ok)
                return

            goods_id = self.goods_id_search_edit.text().strip()
            goods_name = self.goods_name_search_edit.text().strip()
            goods_type = self.goods_type_search_box.currentData()
            goods_price = self.goods_price_search_edit.text().strip()
            goods_supplier = self.goods_supplier_search_edit.text().strip()

            # 调用 GoodDao 的方法获取商品信息
            good_list = GoodDao.get_good_by_name_supplier_type(
                self.driver, good_id=goods_id, good_name=goods_name, supplier=goods_supplier,
                good_type=(goods_type,) if goods_type else None, price=goods_price)

            self.goods_listView.clear()

            for good in good_list:
                item = QListWidgetItem(self.goods_listView)
                item.setSizeHint(QSize(850, 50))
                widget = QWidget()
                layout = QHBoxLayout()

                label_id = QLabel("编号: " + str(good[0]))
                label_name = QLabel("名称: " + str(good[1]))
                label_supplier = QLabel("供应商: " + str(good[2]))
                label_type_name = QLabel("类别: " + str(good[3]))
                label_price = QLabel("价格: " + f"{float(good[4]):.2f}")  # 确保价格显示为两位小数
                label_num = QLabel("数量: " + str(good[5]))  # 显示数量

                layout.addWidget(label_id)
                layout.addWidget(label_name)
                layout.addWidget(label_supplier)
                layout.addWidget(label_type_name)
                layout.addWidget(label_price)
                layout.addWidget(label_num)

                widget.setLayout(layout)
                self.goods_listView.addItem(item)
                self.goods_listView.setItemWidget(item, widget)
        except Exception as e:
            print(f"Error searching goods: {e}")  # Debug print statement

    def goods_add(self):
        try:
            good_id = self.goods_id_edit.text().strip()
            good_name = self.goods_name_edit.text().strip()
            good_num = self.goods_num_box.value()
            good_type = self.goods_type_box.currentData()
            good_supplier = self.goods_supplier_edit.text().strip()
            good_price = float(self.goods_price_edit.text().strip())

            print(
                f"Add good with ID: {good_id}, Name: {good_name}, Supplier: {good_supplier}, Type: {good_type}, Num: {good_num}, Price: {good_price}")  # Debug print statement

            if good_id and good_name and good_type and good_supplier and good_price:
                result = GoodDao.insert_good(self.driver, int(good_id), good_name, good_supplier, good_type, good_num,
                                             good_price)
                if result:
                    MessageBoxTools.information('成功', '商品添加成功')
                    self.goods_items_fresh()
                else:
                    MessageBoxTools.warning('错误', '商品添加失败')
            else:
                MessageBoxTools.warning('输入错误', '请填写所有字段')
        except Exception as e:
            print(f"Error adding goods: {e}")  # Debug print statement

    def goods_delete(self):
        try:
            good_id = self.goods_id_edit.text().strip()
            result = GoodDao.del_good(self.driver, good_id)
            if result:
                tools.MessageBoxTools.information(self, '成功', '商品删除成功')
                self.goods_items_fresh()
            else:
                tools.MessageBoxTools.warning(self, '错误', '商品删除失败，可能商品编号不存在')
        except Exception as e:
            print(f"Error deleting goods: {e}")  # Debug print statement

    from PyQt5.QtWidgets import QMessageBox

    def goods_update(self):
        try:
            good_id = self.goods_id_edit.text().strip()
            good_name = self.goods_name_edit.text().strip()
            good_num = self.goods_num_box.value()
            good_type = self.goods_type_box.currentData()
            good_supplier = self.goods_supplier_edit.text().strip()

            if good_id and good_name and good_type and good_supplier:
                result = GoodDao.update_good(self.driver, int(good_id), good_name, good_supplier, good_type, good_num)
                if result:
                    MessageBoxTools.information('成功', '商品更新成功')
                    self.goods_items_fresh()
                else:
                    MessageBoxTools.warning('错误', '商品更新失败')
            else:
                MessageBoxTools.warning('输入错误', '请填写所有字段')
        except Exception as e:
            print(f"Error updating goods: {e}")  # 调试打印语句


if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    window = goodsManagementPage(user_id=1)
    sys.exit(app.exec_())
